#pragma once
#include <functional>
#include "Common.hpp"
#include "Socket.hpp"
#include "InetAddr.hpp"
#include "Protocol.hpp"
#include "Connection.hpp"
#include "NetCal.hpp"
using namespace sock_ns;

class PackpageParse
{
public:
    PackpageParse() {}
    ~PackpageParse() {}
    void Excute(Connection *con) // 执行分割报文
    {
        std::string packagestream;
        while (true)
        {
            // 确定报文是否完整？
            std::string package = Decode(con->RecvBuffer());
            if (package.empty())
                break; // 如果不是完整的报文就退出循环

            std::shared_ptr<Request> req = Factor::BuildRequestDefault();
            // 对client发过来的请求进行反序列化
            req->Deserialization(package);
            // 业务处理
            std::shared_ptr<Respence> resp = _cal.CalWork(req); // 发出请求，接收一个回应
            std::string res_package;

            //  对返回的应答进行序列化
            resp->Serialization(&res_package);
            std::cout << "res_package: \n"
                      << res_package << std::endl;
            // 形成完整报文
            std::string respjson = Encode(res_package);
            std::cout << "respjson add header done: \n"
                      << respjson << std::endl;
            // 添加进缓冲区
            con->AppendSendBuffer(respjson);
        }
        // 方案1.发回
        if (!con->SendBuffer().empty())
            con->_send_handle(con);
        //2.激活对于特定事件的关心即可
        // if (!con->SendBuffer().empty())
        //     con->_R->EnableConnectionReadWrite(con->SockFd(),true,true);
    }

private:
    NetCal _cal;
};
